package com.bjh.codec;

import com.bjh.model.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

public class MessageEncoder extends MessageToByteEncoder<Message> {

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf out) throws Exception {
        out.writeInt(message.getMessageHead().getCommond());
        out.writeInt(message.getMessageHead().getVersion());
        out.writeInt(message.getMessageHead().getClientType());
        out.writeInt(message.getMessageHead().getMessageType());
        out.writeInt(message.getMessageBody().getImei().getBytes(Charset.forName("utf-8")).length);
        out.writeInt(message.getMessageHead().getAppId());
        out.writeInt(message.getMessageBody().getData().toString().getBytes(Charset.forName("utf-8")).length);
        String paramsTypesBody = objectMapper.writeValueAsString(message.getMessageBody().getParams());
        out.writeInt(paramsTypesBody.getBytes(Charset.forName("utf-8")).length);

        out.writeBytes(message.getMessageBody().getImei().getBytes(Charset.forName("utf-8")));
        out.writeBytes(message.getMessageBody().getData().toString().getBytes(Charset.forName("utf-8")));
        out.writeBytes(paramsTypesBody.getBytes(Charset.forName("utf-8")));
    }
}
